<html>
<style>
    html,
    body {
        margin: 0;
        height: 100%;
    }

    ul {
        list-style: none;
        margin: 0;
        padding: 0;
        display: flex;
        justify-content: center;
    }

    .box {
        width: 100%;
        height: 100%;
        background-color: red;
    }
</style>

<body>
    <ul>
        <li>
            <a href="#red">红色</a>
        </li>
        &nbsp;&nbsp;&nbsp;
        <li>
            <a href="#green">绿色</a>
        </li>
        &nbsp;&nbsp;&nbsp;
        <li>
            <a href="#purple">紫色</a>
        </li>
    </ul>
    <div class="box"></div>

    <!-- <script>
        let box = document.getElementsByClassName("box")[0];

        window.onhashchange = function () {
            let color = location.hash.slice(1);
            box.style.background = color
        }
    </script> -->

    <script>
        // 封装成一个类
        let box = document.getElementsByClassName("box")[0];

        class HashRouter {
            constructor(hashStr, cb) {
                this.hashStr = hashStr;
                this.cb = cb;
                this.watchHash()
                window.addEventListener("hashchange", this.watchHash.bind(this))
            }
            watchHash() {
                let hash = location.hash.slice(1)
                this.hashStr = hash;
                this.cb(this.hashStr)
            }
        }

        new HashRouter("red", (color) => {
            box.style.background = color;
        });
    </script>
</body>

</html>